<?php

namespace addons\helper\controller\wxapp;

use addons\helper\controller\wxapp\Base;
use fast\Tree;

class Category extends Base
{
    protected $searchFields = 'id';
    protected $config = [
        'model'        => '分类',
        'limit'        => 10,
        'defaultSort'  => 'id',
        'defaultOrder' => 'desc',
        'multi'        => true,
        'field' => [
            'pid'         => ['父级', 'select', false,  false, '', true, true, true],
            'type'        => ['类型', 'select', false,  false, '', true, true, true],
            'name'        => ['名称', 'text', false,  false, '', true, true, true],
            'nickname'    => ['昵称', 'text', false,  false, '', true, true, true],
            'flag'        => ['标志', 'selects', false,  false, '', true, true, true],
            'image'       => ['图片', 'image', false,  false, '', true, true, true],
            'keywords'    => ['关键字', 'text', false,  false, '', true, true, true],
            'description' => ['描述', 'text', false, false, '', true, true, true],
            'diyname'     => ['自定义名称', 'text', false, false, '', true, true, true],
            'createtime'  => ['创建时间', 'datetime', false, false, '', true, false, false],
            'updatetime'  => ['更新时间', 'datetime', false, false, '', true, false, false],
            'weigh'       => ['权重', 'number', false, false, '', true, true, true],
            'status'      => ['状态', 'select', false, false, '', true, true, true],
        ],
        'fieldContent' => [
            'pid'   => [],
            'type'  => [],
            'flag'  => [],
            'status' => [
                'normal' => '正常',
                'hidden' => '隐藏'
            ]
        ],
        // [可选]前端表单验证规则
        'rules' => [
            'pid' => [
                'required'    => true
            ],
            'type' => [
                'required'    => true
            ],
            'name' => [
                'required'    => true
            ],
            'nickname' => [
                'required'    => true
            ]
        ], 
        'auth' => [
            'add'  => [
                'name' => '添加',
                'url'  => 'category/add',
            ],
            'edit'  => [
                'name' => '编辑',
                'url'  => 'category/edit',
            ],
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'color'       => '#e74c3c',
                    'icon'        => 'fa-trash',
                    'url'         => 'category/del'
                ],
                'hidden'  => [
                    'name'        => '设为隐藏',
                    'color'       => '#f39c12',
                    'icon'        => 'fa-eye-slash',
                    'url'         => 'category/multi',
                    'params'      => 'status=hidden'
                ],
                'normal'  => [
                    'name'        => '设为正常',
                    'color'       => '#18bc9c',
                    'icon'        => 'fa-eye',
                    'url'         => 'category/multi',
                    'params'      => 'status=normal'
                ],
                
            ],
            'more' => [
                'del'  => [
                    'name'  => '删除',
                    'color' => '#e74c3c',
                    'url'   => 'category/del'
                ],
                'hidden'  => [
                    'name'        => '设为隐藏',
                    'color'       => '#f39c12',
                    'url'         => 'category/multi',
                    'params'      => 'status=hidden'
                ],
                'normal'  => [
                    'name'        => '设为正常',
                    'color'       => '#18bc9c',
                    'url'         => 'category/multi',
                    'params'      => 'status=normal'
                ],
            ],
        ],
        'tabField'          => 'type',
        'searchPlaceholder' => '输入ID搜索',
    ];

    protected $categorylist = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Category;
        $this->config['field'] = $this->formatField();
        $this->config['pk'] = $this->model->getPk() ? $this->model->getPk() : 'id';

        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid', '　');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        //构造父类select列表选项数据
        $categorydata[] = __('None');
        foreach ($this->categorylist as $k => $v) {
            $categorydata[] = [
                $v['id'] => $v['name']
            ];
        }
        $this->config['fieldContent']['pid']  = $categorydata;
        $this->config['fieldContent']['type'] = $this->model->getTypeList();
        $this->config['fieldContent']['flag'] = $this->model->getFlagList();
    }
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            $search = $this->request->post('search');
            $filter = json_decode($this->request->post('filter'),true);
            $type   = isset($filter['type']) ? $filter['type'] : '';

            $list = [];
            foreach ($this->categorylist as $k => $v) {
                if ($search) {
                    if ($v['type'] == $type && stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false) {
                        if ($type == 'all' || $type == null) {
                            $list = $this->categorylist;
                        } else {
                            $list[] = $v;
                        }
                    }
                } else {
                    if ($type == 'all' || $type == null) {
                        $list = $this->categorylist;
                    } elseif ($v['type'] == $type) {
                        $list[] = $v;
                    }
                }
            }
            $total = count($list);
            $result = array('total' => $total, 'rows' => $list);
            $tabList[] = array('id' => 'all', 'name' => '全部');
            foreach ($this->config['fieldContent']['type'] as $k => $v) {
                $tabList[] = array('id' => $k, 'name' => $v);
            }
            $data = [
                'tabList'  => $tabList,
                'dataList' => $result,
                'config'   => $this->config
            ];
            $this->success('ok', $data);
        }
    }
    public function edit ()
    {
        $ids = $this->request->get('ids');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($params['pid'] != $row['pid']) {
                    $childrenIds = Tree::instance()->init(collection(\app\common\model\Category::select())->toArray())->getChildrenIds($row['id'], true);
                    if (in_array($params['pid'], $childrenIds)) {
                        $this->error(__('Can not change the parent to child or itself'));
                    }
                }

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }else{
            return parent::edit();
        }
    }
        
}
